package com.qunar.tech.team12.notepad.notepad;

import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Closer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;

/**
 * Created by mzy on 14-7-21.
 */
public class Notepad {

    private static final Splitter OR = Splitter.on("|");
    private static final Splitter COLON = Splitter.on(":");
    private static final Splitter SPACE = Splitter.on(" ");

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    private Map<String, Map<String, String>> notepad = Maps.newHashMap();
    private File file;

    public Notepad(File file) {
        this.file = file;
    }

    public Notepad write(String user, String title, String content) {
        Map<String, String> record = notepad.get(user);
        if (record == null) {
            record = Maps.newHashMap();
            record.put(title, content);
            notepad.put(user, record);
        }
        return this;
    }

    public String read(String user, String title) {
        loadFromDisk();
        Map<String, String> record = notepad.get(user);
        if (record != null) {
            return record.get(title);
        }
        return "";
    }

    private void loadFromDisk() {
        Closer closer = Closer.create();
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
            closer.register(objectInputStream);
            notepad = (Map<String, Map<String, String>>) objectInputStream.readObject();
        } catch (IOException e) {
            LOG.error("error occurred in reading object from {}", file.getName(), e);
        } catch (ClassNotFoundException e) {
            LOG.error("error occurred in unserialize from file {}", file.getName(), e);
        } finally {
            try {
                closer.close();
            } catch (IOException e) {
                LOG.error("error occurred in closing ObjectInputStream {}", file.getName(), e);
            }
        }
    }

    public void sync() {
        Closer closer = Closer.create();
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
            closer.register(objectOutputStream);
            objectOutputStream.writeObject(notepad);
        } catch (IOException e) {
            LOG.error("error occurred in writing object to {}", file.getName(), e);
        } finally {
            try {
                closer.close();
            } catch (IOException e) {
                LOG.error("error occurred in closing ObjectOutputStream {}", file.getName(), e);
            }
        }
    }
}
